package com.it.gw.modules.water.activity.jijing

import ADNMVo
import android.content.Intent
import android.util.Log
import android.view.View
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.Toast
import androidx.activity.viewModels
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.it.common.bean.MapDataBean
import com.it.common.utils.GsonUtils
import com.it.common.utils.RvSpacesItemUtils
import com.it.common.utils.isNotEmpty
import com.it.data.network.req.WellRecordDto
import com.it.gw.R
import com.it.gw.base.BaseActivity
import com.it.gw.databinding.ActivityJijingItemDetailBinding
import com.it.gw.databinding.LayoutPopAddvcdSelectBinding
import com.it.gw.dialog.ProgressDialog
import com.it.gw.manager.DictionariesManager
import com.it.gw.manager.DictionariesManager.wasoType
import com.it.gw.manager.DictionariesManager.wellType
import com.it.gw.manager.DictionariesManager.wellUseType
import com.it.gw.modules.map.activity.MapActivity
import com.it.gw.modules.water.adapter.ADDVCDAdapter
import com.it.gw.modules.water.viewmodel.WaterViewModel

//机井详情
class JiJingItemDetailActivity : BaseActivity<ActivityJijingItemDetailBinding>() {
    private val waterViewModel by viewModels<WaterViewModel>()

    companion object {
        const val TAG = "DouQuItemDetailActivity"
    }


    override fun initObserver() {
        waterViewModel.wellRecordDtoDetailLiveData.observe(this) {
            ProgressDialog.hide()
            Log.d(TAG, "douQRecordDtoDetailLiveData: ${it}")
            if (it.result && it.data.isNotEmpty()) {
                setDetailView(it.data!!)
            }

        }
        waterViewModel.insertLiveData.observe(this) {
            ProgressDialog.hide()
            if (it.result) {
                Toast.makeText(this, "操作成功", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "${it.msg}", Toast.LENGTH_SHORT).show()
            }

        }


    }

    //师
    var division: String? = null

    //团
    var regiment: String? = null
    private fun setDetailView(data: WellRecordDto) {
        division = data.division
        regiment = data.regiment
        binding.lttd.setText(data.lttd) // 纬度
        binding.lgtd.setText(data.lgtd) // 取水井经度
        binding.wellCode.setText(data.wellCode) // 取水井代码
        binding.wellName.setText(data.wellName) // 取水井名称
        binding.wellLoc.setText(data.wellLoc) // 取水井所在位置
        binding.wellDep.setText(data.wellDep) // 井深(M)
        binding.wellInnDiam.setText(data.wellInnDiam) // 井口共管内径(mm)
        binding.pipeMat.setText(data.pipeMat) // 井壁管材料
        binding.compYear.setText(data.compYear) // 成井年份
        binding.desAnnWain.setText(data.desAnnWain) // 设计年取水量
        // binding.wasoType.setText(data.wasoType) // 水源类型

        //水源类型
        binding.wasoType.setText(
            DictionariesManager.findNameByCode(
                list = DictionariesManager.dictionariesMap.get(wasoType),
                code = data.wasoType
            )
        )



        binding.wellMeterCode.setText(data.wellMeterCode) // 水表编号
        // binding.wellType.setText(data.wellType) // 水井类型

        //水井类型
        binding.wellType.setText(
            DictionariesManager.findNameByCode(
                list = DictionariesManager.dictionariesMap.get(wellType),
                code = data.wellType
            )
        )


        //  binding.wellUseType.setText(data.wellUseType) // 水井用途

        //水井用途
        binding.wellUseType.setText(
            DictionariesManager.findNameByCode(
                list = DictionariesManager.dictionariesMap.get(wellUseType),
                code = data.wellUseType
            )
        )



        binding.yearWater.setText(data.yearWater) // 年用水量
        binding.note.setText(data.note) // 备注


        mainViewModel.getShiAddvcd(resp = { s ->
            Log.d(TAG, "getShiAddvcd: ${s.data}")
            if (s.data.isNotEmpty()) {
                val shi = s.data?.find { it.ADDVCD == division }
                if (shi.isNotEmpty()) {
                    binding.division.setText(shi?.ADNM) // 师
                    mainViewModel.getTuanAddvcd(id = shi!!.ADDVCD, resp = { t ->
                        ProgressDialog.hide()
                        Log.d(TAG, "getTuanAddvcd: ${t.data}")
                        if (t.data.isNotEmpty()) {
                            val tuan = t.data?.find { it.ADDVCD == regiment }
                            binding.regiment.setText(tuan!!.ADNM) // 团
                        }

                    })

                }

            }

        })


    }


    override fun initListener() {

        binding.lgtd.setOnClickListener {
            startLocation()
        }
        binding.lttd.setOnClickListener {
            startLocation()
        }

        binding.btnSave.setOnClickListener {
            insertDouQRecord()

        }
        binding.compYear.setOnClickListener {
            showYearPickerDialog(selectYearAction = {
                binding.compYear.text = it.toString()
            })
        }
        binding.wasoType.setOnClickListener {
            DictionariesManager.dictionariesMap.get(wasoType)?.let { it1 ->
                showDictionariesWheelViewDialog(
                    dataList = it1,
                    okAction = { index ->
                        binding.wasoType.text =
                            DictionariesManager.dictionariesMap.get(wasoType)!![index].ITEMNAME

                    })
            }
        }
        binding.wellType.setOnClickListener {
            DictionariesManager.dictionariesMap.get(wellType)?.let { it1 ->
                showDictionariesWheelViewDialog(
                    dataList = it1,
                    okAction = { index ->
                        binding.wellType.text =
                            DictionariesManager.dictionariesMap.get(wellType)!![index].ITEMNAME

                    })
            }
        }

        binding.wellUseType.setOnClickListener {
            DictionariesManager.dictionariesMap.get(wellUseType)?.let { it1 ->
                showDictionariesWheelViewDialog(
                    dataList = it1,
                    okAction = { index ->
                        binding.wellUseType.text =
                            DictionariesManager.dictionariesMap.get(wellUseType)!![index].ITEMNAME

                    })
            }
        }
        binding.division.setOnClickListener {
            ProgressDialog.show(this)
            mainViewModel.getShiAddvcd(resp = {
                ProgressDialog.hide()
                Log.d(TAG, "getShiAddvcd: ${it.data}")
                if (it.data.isNotEmpty()) {
                    showSelectShiTuanPopupWindow(binding.vTop, shiList = it.data!!)
                }

            })
        }
        binding.regiment.setOnClickListener {
            ProgressDialog.show(this)
            mainViewModel.getShiAddvcd(resp = {
                ProgressDialog.hide()
                Log.d(TAG, "getShiAddvcd: ${it.data}")
                if (it.data.isNotEmpty()) {
                    showSelectShiTuanPopupWindow(binding.vTop, shiList = it.data!!)
                }

            })
        }

    }

    private lateinit var shiAdapter: ADDVCDAdapter
    private lateinit var tuanAdapter: ADDVCDAdapter
    private lateinit var addvcdSelectBinding: LayoutPopAddvcdSelectBinding
    private val tuanList = mutableListOf<ADNMVo>()
    private fun showSelectShiTuanPopupWindow(anchor: View, shiList: List<ADNMVo>) {
        addvcdSelectBinding = LayoutPopAddvcdSelectBinding.inflate(layoutInflater)
        val popupWindow = PopupWindow(
            addvcdSelectBinding.root,
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )
        val map = HashMap<String, Int>()
        //间距
        map[RvSpacesItemUtils.BOTTOM_DECORATION] = 1
        addvcdSelectBinding.rvShi.addItemDecoration(RvSpacesItemUtils(map))
        shiList[0].selected = true
        selectShi(shiList[0])
        shiAdapter = ADDVCDAdapter(datas = shiList, context = this, listener = {
            for (i in shiList.indices) {
                if (shiList[i].ADDVCD == it.ADDVCD) {
                    shiList[i].selected = true
                    selectShi(it)
                } else {
                    shiList[i].selected = false
                }
            }
            shiAdapter.notifyDataSetChanged()

        })
        addvcdSelectBinding.rvShi.adapter = shiAdapter
        //团
        addvcdSelectBinding.rvTuan.addItemDecoration(RvSpacesItemUtils(map))
        tuanAdapter = ADDVCDAdapter(datas = tuanList, context = this, listener = {
            for (i in tuanList.indices) {
                if (tuanList[i].ADDVCD == it.ADDVCD) {
                    tuanList[i].selected = true
                    selectTuan(it)

                } else {
                    tuanList[i].selected = false
                }
            }
            popupWindow.dismiss()
            tuanAdapter.notifyDataSetChanged()

        })
        addvcdSelectBinding.rvTuan.adapter = tuanAdapter


        // 设置 PopupWindow 的其他属性
        popupWindow.isFocusable = true
        addvcdSelectBinding?.vOutSide?.setOnClickListener {
            popupWindow.dismiss()
        }
        addvcdSelectBinding?.rlCancel?.setOnClickListener {
            popupWindow.dismiss()
        }

        // 显示 PopupWindow
        popupWindow.showAsDropDown(anchor)

    }

    private var adnmTuanVo: ADNMVo? = null
    private fun selectTuan(vo: ADNMVo) {
        adnmTuanVo = vo
        setXZQHView()
    }

    private var adnmShiVo: ADNMVo? = null
    private fun selectShi(vo: ADNMVo) {
        adnmShiVo = vo
        ProgressDialog.show(this)
        mainViewModel.getTuanAddvcd(id = vo.ADDVCD, resp = {
            ProgressDialog.hide()
            Log.d(TAG, "getTuanAddvcd: ${it.data}")
            if (it.data.isNotEmpty()) {
                tuanList.clear()
                tuanList.addAll(it.data!!)
                tuanList.get(0).selected = true
                tuanAdapter.notifyDataSetChanged()
            }

        })

    }

    private fun setXZQHView() {
        if (!adnmTuanVo.isNotEmpty()) {
        } else {
            division = adnmShiVo?.ADDVCD
            regiment = adnmTuanVo?.ADDVCD
            binding.division.text = adnmShiVo?.ADNM
            binding.regiment.text = adnmTuanVo?.ADNM

        }

    }

    private fun insertDouQRecord() {
        ProgressDialog.show(this)
        val dto = WellRecordDto(
            lgtd = binding.lgtd.text.toString(), // 泵站经度
            wellCode = binding.wellCode.text.toString(), // 取水井代码
            wellName = binding.wellName.text.toString(), // 取水井名称
            lttd = binding.lttd.text.toString(), // 取水井纬度
            wellLoc = binding.wellLoc.text.toString(), // 取水井所在位置
            wellDep = binding.wellDep.text.toString(), // 井深(M)
            wellInnDiam = binding.wellInnDiam.text.toString(), // 井口共管内径(mm)
            pipeMat = binding.pipeMat.text.toString(), // 井壁管材料
            compYear = binding.compYear.text.toString(), // 成井年份
            desAnnWain = binding.desAnnWain.text.toString(), // 设计年取水量
            // wasoType = binding.wasoType.text.toString(), // 水源类型

            wasoType = DictionariesManager.findCodeByName(
                list = DictionariesManager.dictionariesMap.get(wasoType),
                name = binding.wasoType.text.toString()
            ),

            wellMeterCode = binding.wellMeterCode.text.toString(), // 水表编号
            // wellType = binding.wellType.text.toString(), // 水井类型

            wellType = DictionariesManager.findCodeByName(
                list = DictionariesManager.dictionariesMap.get(wellType),
                name = binding.wellType.text.toString()
            ),
            // wellUseType = binding.wellUseType.text.toString(), // 水井用途

            wellUseType = DictionariesManager.findCodeByName(
                list = DictionariesManager.dictionariesMap.get(wellUseType),
                name = binding.wellUseType.text.toString()
            ),
            division = division, // 师
            regiment = regiment, // 团
            yearWater = binding.yearWater.text.toString(), // 年用水量
            note = binding.note.text.toString() // 备注
        )
        waterViewModel.insertWellRecord(dto)

    }

    override fun initData() {
        ProgressDialog.show(this)
        getData()
    }

    private fun getData() {
        waterViewModel.getWellBasic(intent.getStringExtra("id")!!)

    }


    var title = ""
    override fun initView() {
        DictionariesManager.getJDJDictionaries()
        title = "${intent.getStringExtra("title")}"
        setTitle(
            title = title,
            isBack = true,
            tvRightRes1 = R.string.str_location,
            tvRight1Action = {
                val intent = Intent(this, MapActivity::class.java)
                intent.putExtra("title", title)
                val mapList = mutableListOf(
                    MapDataBean(
                        name = title,
                        lgtd = binding.lgtd.text.toString(),
                        lttd = binding.lttd.text.toString(),
                    )
                )
                intent.putExtra(MapActivity.MAP_DATA, GsonUtils.objToJsonStr(mapList))
                startActivity(intent)
            }

        )

    }

    override fun setContentView() {
        binding = ActivityJijingItemDetailBinding.inflate(layoutInflater)
        setContentView(binding.root)
    }

    //声明AMapLocationClientOption对象
    private var mLocationOption: AMapLocationClientOption? = null

    //声明AMapLocationClient类对象
    private var mLocationClient: AMapLocationClient? = null
    private fun startLocation() {
        Log.d(TAG, "startLocation: ===========")
        mLocationClient = AMapLocationClient(applicationContext)
        mLocationClient?.setLocationListener(object : AMapLocationListener {
            override fun onLocationChanged(p0: AMapLocation?) {
                val longitude = "${p0?.longitude}"
                val latitude = "${p0?.latitude}"
                Log.d(TAG, "onLocationChanged: ${longitude} ${latitude}")
                binding.lttd.setText(latitude)
                binding.lgtd.setText(longitude)

            }

        })

        mLocationOption = AMapLocationClientOption()
        val option = AMapLocationClientOption()
        option.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn)
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        option.setOnceLocation(true);
        option.setOnceLocationLatest(true);

        if (null != mLocationClient) {
            mLocationClient?.setLocationOption(option)
            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
            mLocationClient?.stopLocation()
            mLocationClient?.startLocation()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mLocationClient?.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
    }


}